package com.radio.helper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;

import com.radio.RadioApplication;

public class FileHelper {
	private final String TAG = "FileHelper";
	private final String DIRECTORY = "/Radio";
	private final String FILE_EXT = ".mp3";
	private String dir;
	private boolean isWrite;
	private File outputFile;
	private FileOutputStream fileOutputStream;
	private InputStream instream;
	private int bytesRead = 0;
	
	public void startRecord(Activity activity, String fileName){
		instream = ((RadioApplication)activity.getApplication()).getInstream();
		if (storageOk()){
			dir = Environment.getExternalStorageDirectory().toString() + DIRECTORY;
			File folder = new File(dir);
			if (!folder.exists()){
				folder.mkdir();
			}
			
			outputFile = new File(dir + "/" + fileName + FILE_EXT);
			fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(outputFile);
			} catch (FileNotFoundException e1) {
				Log.e(TAG, e1.getMessage());
			}
			
			isWrite = true;
	        new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
			        	while (isWrite){
			        		fileOutputStream.write(instream.read());
			        		bytesRead++;
			        	}
					} catch (IOException e) {
						Log.e(TAG, e.getMessage());
					}
				}
			});
	        
		}
	}
	
	/**
	 * Check if we can use external storage
	 * @return
	 */
	private boolean storageOk(){
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)){
			return true;
		}else{
			return false;
		}
	}
	
	public void stopRecord() {
		isWrite = false;
		try {
			fileOutputStream.close();
			Log.i(TAG, "==Bytes read === " + bytesRead);
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
	}
}
